home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C22 / MultipleInheritance4.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.2 KB  |  57 lines

  1. //: C22:MultipleInheritance4.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // "Tying off" virtual bases
  7. // so you don't have to worry about them
  8. // in derived classes
  9. #include "../purge.h"
  10. #include <iostream>
  11. #include <vector>
  12. using namespace std;
  13.  
  14. class MBase {
  15. public:
  16.  // Default constructor removes responsibility:
  17.   MBase(int = 0) {}
  18.   virtual char* vf() const = 0;
  19.   virtual ~MBase() {}
  20. };
  21.  
  22. class D1 : virtual public MBase {
  23. public:
  24.   D1() : MBase(1) {}
  25.   char* vf() const { return "D1"; }
  26. };
  27.  
  28. class D2 : virtual public MBase {
  29. public:
  30.   D2() : MBase(2) {}
  31.   char* vf() const { return "D2"; }
  32. };
  33.  
  34. class MI : public D1, public D2 {
  35. public:
  36.   MI() {} // Calls default constructor for MBase
  37.   char* vf() const {
  38.     return D1::vf(); // MUST disambiguate
  39.   }
  40. };
  41.  
  42. class X : public MI {
  43. public:
  44.   X() {} // Calls default constructor for MBase
  45. };
  46.  
  47. int main() {
  48.   vector<MBase*> b;
  49.   b.push_back(new D1);
  50.   b.push_back(new D2);
  51.   b.push_back(new MI); // OK
  52.   b.push_back(new X);
  53.   for(int i = 0; i < b.size(); i++)
  54.     cout << b[i]->vf() << endl;
  55.   purge(b);
  56. } ///:~
  57.